<template>
  <div class="page">
    <div class="toolform">
      <div class="form-content">
        <VSelectPlus
          v-model="form.currency"
          url="/exchangeRate/options"
          placeholder="币种"
          valueField="label"
        />
        <div style="width: 360px">
          <el-date-picker
            v-model="form.time"
            type="daterange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate"
          />
        </div>
        <div class="form-handle">
          <el-button type="primary" @click="query">查询</el-button>
          <el-button @click="clear" class="ml-[0px]">重置</el-button>
        </div>
      </div>
    </div>

    <div class="table-content">
      <vxe-grid v-bind="gridOptions" ref="tableRef">
        <template #toolbar_btns>
          <VActionBar :actions="actions" />
        </template>
      </vxe-grid>
    </div>
    <SetChannel
      v-model="setChannelVisible"
      :optionData="optionData"
      :data="setChannelData"
      @close="setChannelData = []"
    />
    <ChannelRate
      v-model="channelRateVisible"
      :data="channelRateData"
      :currency="form.currency"
      @close="channelRateData = []"
    />
  </div>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import rangeTime from "@/components/rangeTime/index.vue";
import SetChannel from "./SetChannel/index.vue";
import ChannelRate from "./ChannelRate/index.vue";
import {
  getCurrentDate,
  getPastDateRange,
  decomposeDateRange,
} from "@/utils/time.js";
import { getChannelList } from "@/views/base/channel/api.js";
import { getExchangeRateList } from "../../api.js";
const form = ref({
  currency: "USD",
  time: getPastDateRange(),
});
const tableRef = ref();
const columnsData = ref([]);
const columnsOriginal = ref([
  {
    title: "换汇渠道",
    field: "channelName",
    width: 100,
    fixed: "left",
  },
]);

const columnsRight = ref([
  {
    title: "汇率差",
    field: "rateDifference",
    width: 90,
  },
  {
    title: "操作",
    width: 90,
    fixed: "right",
    slots: {
      default: ({ row }) => {
        return (
          <div>
            <el-button type="text" size="mini" onClick={() => handleRate(row)}>
              更新汇率
            </el-button>
          </div>
        );
      },
    },
  },
]);

const gridOptions = reactive({
  height: "auto",
  columnConfig: {
    resizable: true,
  },
  loading: false,
  size: "mini",
  toolbarConfig: {
    slots: {
      buttons: "toolbar_btns",
    },
  },
  columns: [...columnsOriginal.value, ...columnsRight.value],
  data: [],
});
const refresh = () => {
  tableRef.value.commitProxy("reload");
};
onMounted(() => {
  getList();
  getChannel();
});
const getList = async () => {
  try {
    const { time } = form.value;
    const submit = {
      ...form.value,
      baseAtStart: `${time[0]} 00:00:00` || undefined,
      baseAtEnd: `${time[1]} 23:59:59` || undefined,
      time: undefined,
    };
    gridOptions.loading = true;
    const { data } = await getExchangeRateList(submit);
    let dataTime = decomposeDateRange(time);
    let columns = dataTime.map((item, index) => ({
      title: item,
      field: `day${index}`,
      width: 110,
    }));
    columnsData.value = columns;
    gridOptions.columns = [
      ...columnsOriginal.value,
      ...columnsData.value,
      ...columnsRight.value,
    ];
    tableRef.value?.resetColumn();
    data?.forEach((item) => {
      const result = {};
      item.channelId = BigInt(item?.channelId)?.toString();
      item.exchangeRates?.forEach((rate, index) => {
        result[`day${index}`] = rate;
      });
      item.rateDifference = 0;
      Object.assign(item, result);
    });
    gridOptions.data = data;
  } catch (error) {
  } finally {
    gridOptions.loading = false;
  }
};
const optionData = ref({});
const getChannel = async () => {
  const { data } = await getChannelList({
    pageNum: 1,
    pageSize: 100,
  });
  data.forEach((item) => {
    item.id = BigInt(item?.id)?.toString();
  });
  let list = data.filter((item) => item.state.value === 1);
  optionData.value.channel = list;
};
const query = () => {
  getList();
};
// 设置换汇渠道
const setChannelVisible = ref(false);
const setChannelData = ref([]);
const handleSetChannel = () => {
  setChannelVisible.value = true;
  setChannelData.value = gridOptions.data;
};
//更新汇率
const handleRate = () => {
  ElMessage.success("更新汇率");
};
// 更新渠道汇率
const channelRateVisible = ref(false);
const channelRateData = ref([]);
const handleChannelRate = () => {
  channelRateVisible.value = true;
  channelRateData.value = gridOptions.data;
};
// 导入汇率
const handleImportRate = () => {
  console.log("导入汇率");
  ElMessage.success("导入汇率");
};
// 导出
const handleExport = () => {
  console.log("导出");
  ElMessage.success("导出");
};
const actions = [
  {
    label: "设置换汇渠道",
    type: "primary",
    fn: () => handleSetChannel(),
  },
  {
    label: "更新渠道汇率",
    fn: () => handleChannelRate(),
  },
  {
    label: "导入汇率",
    right: true,
    fn: () => handleImportRate(),
  },
  // {
  //   label: "导出",
  //   right: true,
  //   fn: () => handleExport(),
  // },
];
const disabledDate = (time) => {
  return getCurrentDate(time);
};
const clear = () => {
  form.value = {
    currency: "USD",
    time: getPastDateRange(),
  };
  getList();
};
</script>
<style scoped lang="scss">
.page {
  height: calc(100% - 40px);
  width: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  padding: 0 10px;
}
.table-content {
  flex: 1;
  display: flex;
  min-height: 0;
  flex-direction: column;
  margin-top: 1px;
  position: relative;
  box-sizing: border-box;
  :deep(.el-button + .el-button) {
    margin-left: 8px;
  }
}
.toolform {
  display: flex;
  gap: 8px;
  box-shadow: 0 1px var(--base-link-color);
  .form-content {
    padding: 10px 0;
    background-color: var(--base-color);
    border-radius: 6px;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    width: 100%;
    .form-handle {
      display: flex;
      gap: 8px;
      margin-left: auto;
    }
  }
}
</style>
